package com.common.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.common.enums.ApiResult;
import com.common.exception.ErrorException;
import com.common.groovy.model.DataModel;
import com.common.model.SystemApplicationServiceModel;
import com.common.mysql.Where;
import com.common.sevice.SystemApplicationModelService;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Date: 2025/7/15 22:19
 */
@RestController
@RequestMapping("/v1/system-application-service")
public class SystemApplicationServiceController extends Controller<String, SystemApplicationModelService, SystemApplicationServiceModel> {

    private static List<DataModel.Field> initFieldList = new LinkedList<>();

    static {
        DataModel.Field id = new DataModel.Field();
        id.setName("id");
        id.setAliasName("id");
        id.setPrimaryKey(true);
        id.setRequired(true);
        id.setComment("主键id");
        id.setCharset("utf8mb4");
        id.setCollate("utf8mb4_0900_ai_ci");
        id.setType("varchar");
        id.setSort(0);
        id.setMaxLength(36);
        initFieldList.add(id);
        DataModel.Field createBy = new DataModel.Field();
        createBy.setName("create_by");
        createBy.setAliasName("createBy");
        createBy.setPrimaryKey(false);
        createBy.setComment("创建人");
        createBy.setCharset("utf8mb4");
        createBy.setCollate("utf8mb4_0900_ai_ci");
        createBy.setType("varchar");
        createBy.setSort(1);
        createBy.setMaxLength(36);
        initFieldList.add(createBy);
        DataModel.Field createTime = new DataModel.Field();
        createTime.setName("create_time");
        createTime.setAliasName("createTime");
        createTime.setPrimaryKey(false);
        createTime.setComment("创建时间");
        createTime.setCharset("utf8mb4");
        createTime.setCollate("utf8mb4_0900_ai_ci");
        createTime.setType("datetime");
        createTime.setDefaultValue("CURRENT_TIMESTAMP");
        createTime.setSort(2);
        createTime.setMaxLength(0);
        initFieldList.add(createTime);
        DataModel.Field updateBy = new DataModel.Field();
        updateBy.setName("update_by");
        updateBy.setAliasName("updateBy");
        updateBy.setPrimaryKey(false);
        updateBy.setComment("更新人");
        updateBy.setCharset("utf8mb4");
        updateBy.setCollate("utf8mb4_0900_ai_ci");
        updateBy.setType("varchar");
        updateBy.setSort(3);
        updateBy.setMaxLength(36);
        initFieldList.add(updateBy);
        DataModel.Field updateTime = new DataModel.Field();
        updateTime.setName("update_time");
        updateTime.setAliasName("updateTime");
        updateTime.setPrimaryKey(false);
        updateTime.setComment("更新时间");
        updateTime.setCharset("utf8mb4");
        updateTime.setCollate("utf8mb4_0900_ai_ci");
        updateTime.setType("datetime");
        updateTime.setDefaultValue("CURRENT_TIMESTAMP");
        updateTime.setUpdateByCurrentTime(true);
        updateTime.setSort(4);
        updateTime.setMaxLength(0);
        initFieldList.add(updateTime);
        DataModel.Field remarks = new DataModel.Field();
        remarks.setName("remarks");
        remarks.setAliasName("remarks");
        remarks.setPrimaryKey(false);
        remarks.setComment("备注");
        remarks.setCharset("utf8mb4");
        remarks.setCollate("utf8mb4_0900_ai_ci");
        remarks.setType("varchar");
        remarks.setSort(5);
        remarks.setMaxLength(255);
        initFieldList.add(remarks);
        DataModel.Field delFlag = new DataModel.Field();
        delFlag.setName("del_flag");
        delFlag.setAliasName("delFlag");
        delFlag.setPrimaryKey(false);
        delFlag.setDefaultValue("0");
        delFlag.setComment("删除标识（0：未删除 1：已删除）");
        delFlag.setCharset("utf8mb4");
        delFlag.setCollate("utf8mb4_0900_ai_ci");
        delFlag.setType("varchar");
        delFlag.setSort(6);
        delFlag.setMaxLength(1);
        initFieldList.add(delFlag);
    }


    @Override
    public ApiResult add(SystemApplicationServiceModel model) {
        String appId = model.getAppId();
        if (!StringUtils.hasText(appId)){
            throw new ErrorException("应用id不能为空！");
        }
        String name = model.getName();
        SystemApplicationServiceModel serviceModel = service.searchOne(Where.build().field("app_id").equal(appId)
                .and().field("type").notEqual("1")
                .and().field("name").equal(name)
                .and().field("del_flag").equal(0));
        if (!ObjectUtils.isEmpty(serviceModel)){
            throw new ErrorException("名称重复，添加失败");
        }
        String type = model.getType();
        JSONObject data = model.getData();
        if ("3".equals(type) && ObjectUtils.isEmpty(data)) {
            for (int i = 0; i < initFieldList.size(); i++) {
                DataModel.Field field = initFieldList.get(i);
                field.setId(System.currentTimeMillis() + i);
            }
            JSONObject dataJsonObject = JSONUtil.createObj();
            dataJsonObject.set("table",JSONUtil.parseObj(new DataModel.Table()));
            dataJsonObject.set("field",JSONUtil.parseArray(initFieldList));
            dataJsonObject.set("action",JSONUtil.createArray());
            model.setData(dataJsonObject);
        }
        return super.add(model);
    }

    /**
     * 树结构查询
     * @param params
     * @return
     */
    @GetMapping("list")
    public ApiResult list(@RequestParam Map<String,Object> params,
                          @RequestParam(required = false) String appId){
        if (!StringUtils.hasText(appId)){
            throw new ErrorException("请选择具体的应用");
        }
        List<SystemApplicationServiceModel> result = service.list(params, appId);
        return ApiResult.success(result);
    }

    /**
     * 模型列表
     * @param appId
     * @return
     */
    @GetMapping("/modelList")
    public ApiResult modelList( @RequestParam(required = false) String appId) {
        if (!StringUtils.hasText(appId)) {
            throw new ErrorException("请选择具体的应用");
        }
        List<SystemApplicationServiceModel> modelList = service.search(Where.build().field("app_id").equal(appId).and().field("type").equal("3")
                .and().field("del_flag").equal(0));
        return ApiResult.success(modelList);
    }

    @Override
    public ApiResult delete(@RequestBody SystemApplicationServiceModel model) {
        if (ObjectUtils.isEmpty(model.getId())){
            throw new ErrorException("主键信息不能为空！");
        }
        //删除子级所有目录和内容
        service.deleteChildren(model.getId());
        return ApiResult.success();
    }
}
